<template>
    <n-card>
        <a :href="fileDl" ref="fileDlRef"></a>
        <n-page-header @back="handleBack">
            <template #title>
                {{ courseName }}
            </template>

            <template #footer>

            </template>
        </n-page-header>
        <n-spin :show="chartShow">
            <n-grid :cols="12" item-responsive responsive="screen">

                <n-gi span="12 m:4 l:4">
                    <div style="width:100%;height:200px" ref="chapterGraph"></div>
                </n-gi>
                <n-gi span="12 m:4 l:4">
                    <div style="width:100%;height:200px" ref="examGraph"></div>
                </n-gi>
                <n-gi span="12 m:4 l:4">
                    <div style="width:100%;height:200px" ref="discussGraph"></div>
                </n-gi>
                <n-gi span="12">
                    <div style="width:100%;height:300px" ref="totalGraph"></div>
                </n-gi>
                <n-gi span="12 m:10 l:10" offset="0 m:1 l:1">
                    <n-card>
                        <BasicTable title="学生列表" titleTooltip="可爱捏" :columns="columns" :request="loadDataTable"
                            :row-key="(row) => row.id" ref="actionRef" :scroll-x="1360" :pagination="false"
                            :resizeHeightOffset="-500">
                            <template #toolbar>
                                <n-space>
                                    <n-button type="success" @click="getExcel">导出表格</n-button>
                                    <n-button type="primary" @click="reloadTable">刷新数据</n-button>
                                </n-space>
                            </template>
                        </BasicTable>
                    </n-card>
                </n-gi>
            </n-grid>
        </n-spin>
    </n-card>
</template>
<script lang="ts" setup>
import { listCourseStudent } from '@/api/teacher/teacherCourse';
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { columns } from './studentList';
import { BasicTable } from '@/components/Table';
import * as echarts from 'echarts';
import { httpFile } from '@/utils/http/axios';

const actionRef = ref();

const route = useRoute();
const router = useRouter();

const chartShow = ref(false);

const handleBack = () => {
    router.go(-1);
}

const params = reactive(
    {
        courseID: route.params.courseID
    }
)

const courseName = ref('');

const chapterGraph = ref();
const examGraph = ref();
const discussGraph = ref();
const totalGraph = ref();

const loadDataTable = async (res) => {
    chartShow.value = true;
    let col = await listCourseStudent({ ...params, ...res });
    // console.log(col.list);
    courseName.value = col.course.courseName;
    let chapterCreditCol = col.list;
    let examCreditCol = col.list;
    let discussCreditCol = col.list;

    chapterCreditCol.sort((a, b) => { return a.chapterCredit > b.chapterCredit });
    examCreditCol.sort((a, b) => { return a.examCredit > b.examCredit });
    discussCreditCol.sort((a, b) => { return a.discussCredit > b.discussCredit });
    //对各行进行排序
    // let chapterGraph: any = document.getElementById('chapterGraph');
    // let examGraph: any = document.getElementById('examGraph');
    // let discussGraph: any = document.getElementById('discussGraph');
    // let totalGraph:any = document.getElementById('totalGraph');
    //对图标dom进行获取
    let mediaChart = echarts.init(chapterGraph.value);
    let examChart = echarts.init(examGraph.value);
    let discussChart = echarts.init(discussGraph.value);
    let totalChart = echarts.init(totalGraph.value);
    //初始化图表

    let cols = chapterCreditCol.slice(0, 5);
    mediaChartOption.yAxis.data = cols.map(a => a.name).reverse();
    mediaChartOption.series[0].data = cols.map(a => a.chapterCredit).reverse();
    mediaChart.setOption(mediaChartOption);
    // 初始化媒体统计
    cols = examCreditCol.slice(0, 5);
    examChartOption.yAxis.data = cols.map(a => a.name).reverse();
    examChartOption.series[0].data = cols.map(a => a.examCredit).reverse();
    examChart.setOption(examChartOption);
    // 初始化测验统计
    cols = discussCreditCol.slice(0, 5);
    discussChartOption.yAxis.data = cols.map(a => a.name).reverse();
    discussChartOption.series[0].data = cols.map(a => a.discussCredit).reverse();
    discussChart.setOption(discussChartOption);
    // 初始化讨论统计
    totalChart.setOption(totalChartOption);
    let totalCredit = col['examSum'] + col['discussSum'] + col['mediaSum'];
    let colCount = [0, 0, 0, 0, 0];
    col.list.forEach(element => {
        console.log(element.totalCredit);
        if (element.totalCredit <= totalCredit * 0.2) colCount[0]++;
        else if (element.totalCredit <= totalCredit * 0.4) colCount[1]++;
        else if (element.totalCredit <= totalCredit * 0.6) colCount[2]++;
        else if (element.totalCredit <= totalCredit * 0.8) colCount[3]++;
        else colCount[4]++;
    });
    totalChartOption.series[0].data = colCount;
    totalChart.setOption(totalChartOption);

    window.addEventListener("resize", (() => {
        setTimeout(() => { // 避免多图同时加载卡顿
            mediaChart.resize();
        }, 200);
        setTimeout(() => { // 避免多图同时加载卡顿
            examChart.resize();
        }, 200);
        setTimeout(() => { // 避免多图同时加载卡顿
            discussChart.resize();
        }, 200);
        setTimeout(() => { // 避免多图同时加载卡顿
            totalChart.resize();
        }, 200);
    }));
    chartShow.value = false;
    return col;

};

const reloadTable = () => {
    actionRef.value.reload();
}

const mediaChartOption = reactive({
    title: {
        text: '多媒体总积分前五名'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    legend: {},
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
    },
    yAxis: {
        type: 'category',
        data: []
    },
    series: [
        {
            name: '积分',
            type: 'bar',
            data: []
        }
    ]
});

const examChartOption = reactive({
    title: {
        text: '测试总积分前五名'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    legend: {},
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
    },
    yAxis: {
        type: 'category',
        data: []
    },
    series: [
        {
            name: '积分',
            type: 'bar',
            data: []
        }
    ]
});

const discussChartOption = reactive({
    title: {
        text: '讨论积分前五名',

    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    legend: {},
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
    },
    yAxis: {
        type: 'category',
        data: []
    },
    series: [
        {
            name: '积分',
            type: 'bar',
            data: []
        }
    ]
});

const colors = ['#5470C6', '#91CC75', '#EE6666'];
const totalChartOption = reactive({
    title: {
        text: '总积分分布统计',
        left: 'center',
        top: '25'
    },
    color: colors,
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        }
    },
    grid: {
        right: '20%'
    },
    toolbox: {
        feature: {
            dataView: { show: true, readOnly: false },
            saveAsImage: { show: true }
        }
    },
    legend: {
        data: ['人数统计'],
    },
    xAxis: [
        {
            type: 'category',
            name: '百分比',
            axisTick: {
                alignWithLabel: true
            },
            // prettier-ignore
            data: ['0-20%', '21-40%', '41-60%', '61-80%', '81-100%']
        }
    ],
    yAxis: [
        {
            type: 'value',
            name: '人数',
            position: 'left',
            alignTicks: true,
            axisLine: {
                show: true,
            }
        }
    ],
    series: [
        {
            name: '人数统计',
            type: 'line',
            smooth: true,
            yAxisIndex: 0,
            data: [0]
        }
    ]
});

const fileDl =ref('')
const fileDlRef = ref()
const getExcel = () => {
    //countCourse
    httpFile.request({
        url: '/teacher/teacher_course/countCourse',
        method: 'GET',
        params: { courseID: route.params.courseID },
        responseType: 'blob'
    }).then((res) => {
        const { data, headers } = res
        console.log(res)
        const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
        // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
        //const blob = new Blob([JSON.stringify(data)], ...)
        const blob = new Blob([data], { type: headers['content-type'] })
        // let dom = document.createElement('a')
        let url = window.URL.createObjectURL(blob)
        fileDl.value = url
        fileDlRef.value.href=url
        fileDlRef.value.download = decodeURI(fileName)
        fileDlRef.value.style.display = 'none'
        // document.body.appendChild(dom)
        fileDlRef.value.click()
        window.URL.revokeObjectURL(url)
    })
}
// option = {
//   xAxis: {
//     type: 'category',
//     data: ['0-20%', '21-40%', '41-60%', '61-80%', '81-100%']
//   },
//   yAxis: {
//     type: 'value'
//   },
//   series: [
//     {
//       data: [820, 932, 901, 934, 1290, 1330, 1320],
//       type: 'line',
//       smooth: true
//     }
//   ]
//};
</script>